import router from "@/router";
import store from "@/store";
import ACCESS_ENUM from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";

// 添加缓存机制，避免重复请求
let isGettingLoginUser = false;
let lastUserCheckTime = 0;
const USER_CACHE_DURATION = 30000; // 30秒缓存

router.beforeEach(async (to, from, next) => {
  console.log("路由跳转:", from.path, "->", to.path);

  let loginUser = store.state.user.loginUser;
  const now = Date.now();

  // 如果用户信息缓存有效且不是首次加载，跳过用户状态检查
  const shouldCheckUser =
    !loginUser ||
    !loginUser.userRole ||
    now - lastUserCheckTime > USER_CACHE_DURATION;

  // 只在必要时获取用户信息
  if (shouldCheckUser && !isGettingLoginUser) {
    try {
      isGettingLoginUser = true;
      console.log("获取登录用户信息...");

      // 加 await 是为了等用户登录成功之后，再执行后续的代码
      await store.dispatch("user/getLoginUser");
      loginUser = store.state.user.loginUser;
      lastUserCheckTime = now;
    } catch (error) {
      console.error("获取用户信息失败:", error);
      // 即使获取失败也继续路由跳转，避免页面卡死
    } finally {
      isGettingLoginUser = false;
    }
  }

  const needAccess = (to.meta?.access as string) ?? ACCESS_ENUM.NOT_LOGIN;

  // 要跳转的页面必须要登陆
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    // 如果没登陆，跳转到登录页面
    if (
      !loginUser ||
      !loginUser.userRole ||
      loginUser.userRole === ACCESS_ENUM.NOT_LOGIN
    ) {
      // 避免无限重定向
      if (to.path !== "/user/login") {
        next(`/user/login?redirect=${to.fullPath}`);
        return;
      }
    }
    // 如果已经登陆了，但是权限不足，那么跳转到无权限页面
    else if (!checkAccess(loginUser, needAccess)) {
      if (to.path !== "/noAuth") {
        next("/noAuth");
        return;
      }
    }
  }

  next();
});
